package web.exercise.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import web.exercise.entity.Contacts;
import web.exercise.exception.NameRepeatException;
import web.exercise.service.ContactsService;
import web.exercise.service.impl.ContactsServiceImpl;

public class AddServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		//接收参数，封装对象
		Contacts contacts=new Contacts();
		contacts.setId(request.getParameter("id"));
		contacts.setName(request.getParameter("name"));
		contacts.setAge(request.getParameter("age"));
		contacts.setGender(request.getParameter("gender"));
		contacts.setQQ(request.getParameter("QQ"));
		contacts.setTelephone(request.getParameter("telephone"));
		contacts.setEmail(request.getParameter("email"));
		//对用户名和id进行判断
		/*boolean judge=AddService.judge(contacts.getId(), contacts.getName());
		boolean result=true;
		if(judge){
			//用户名和id合法
			//传入Dao层写入xml
			ContactsDao dao=new ContactsDaoImpl();
			result=dao.addContacts(contacts);
		}else{
			result=false;
		}*/
		ContactsService service=new ContactsServiceImpl();
		try {
			service.addContacts(contacts);
		} catch (NameRepeatException e) {
			// TODO Auto-generated catch block
			String result=e.getMessage();
			//返回添加成功，写入request域中
			request.setAttribute("addResult", result);
			request.getRequestDispatcher("addContacts.jsp").forward(request, response);
			return;
		}
		boolean result=true;
		request.setAttribute("addResult",result);
		//跳转到主界面
		request.getRequestDispatcher("ShowListServlet").forward(request, response);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}
